import traceback
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import HTTPException
from schemas.baseResponse import BaseResponse
from utils.businessException import BusinessException

def add_exception_handlers(app: FastAPI):
    @app.exception_handler(Exception)
    async def global_exception_handler(request: Request, exc: Exception):

        if isinstance(exc, BusinessException):
            return JSONResponse(
                status_code=exc.status_code,
                content=BaseResponse(code=exc.code, msg=exc.msg).to_dict()
            )
        else:
            tb = traceback.extract_tb(exc.__traceback__)
            last_frame = tb[-1]
            exc={
                "detail": str(exc),
                "line": last_frame.lineno,
                "file": last_frame.filename
            }
            return JSONResponse(
                status_code=500,
                content='ErrorResponse(msg="Internal Server Error", error=exc)'
            )